package org.tinyweb.core;

import org.tinyweb.config.TinyWebConfig;
import org.tinyweb.render.Render;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CoreFilter implements Filter {

    private TinyWeb tinyWeb = TinyWeb.instance();
    private TinyWebConfig tinyWebConfig;

    public void init(FilterConfig fConfig) throws ServletException {
        createTinyWebConfig(fConfig.getInitParameter("app.config"));
        if(tinyWeb.init(tinyWebConfig,fConfig.getServletContext())==false){
            throw new RuntimeException("初始化失败！");
        }
        tinyWeb.getHandler().startupOnLoadHandle();
    }

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	    HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httResponse = (HttpServletResponse)response;
		Render.setContent(httpRequest, httResponse);
        tinyWeb.getHandler().controllerHandle(httpRequest,httResponse);
	}
	
	public void destroy() {
	    //filter destroy
    }

    private void createTinyWebConfig(String configClass){
        if (configClass == null){
            throw new RuntimeException("请在web.xml配置\"app.config\"");
        } else {
            try {
                Object temp = Class.forName(configClass).newInstance();
                if (temp instanceof TinyWebConfig){
                    tinyWebConfig = (TinyWebConfig)temp;
                } else {
                    throw new RuntimeException(configClass + "不能初始化");
                }
            } catch (InstantiationException e) {
                throw new RuntimeException(configClass + "不能初始化");
            } catch (IllegalAccessException e) {
                throw new RuntimeException(configClass + "不能初始化");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("找不到"+configClass+",注意检查\"app.config\"");
            }
        }
    }
}
